import {
    request
} from "../../request/index.js";
import regeneratorRuntime from "../../lib/runtime/runtime";
import {
    getSetting,
    openSetting,
    showModal,
    showToast,
    requestPayment
} from "../../utils/asyncWx.js";

Page({
    data: {
        address: {},
        totalPrice: 0,
        goods_id: "",
        sku_Id:"",
        current_index:0,
        num: 0,
        goodsObj: {}
    },

    onLoad: function(options) {
        const {num,totalPrice,goods_id,current_index} =options;
        this.setData({
            num,
            totalPrice,
            goods_id,
            current_index
        });
    },

    onShow: function() {
        const address = this.getCurrentAddress() || {
            empty: true
        };
        let goodsObj = wx.getStorageSync("goodsObj") || [];
        this.setData({
            address,
            goodsObj
        });
    },

    //点击支付功能
    async handleOrderPay() {
        
        const {address,goodsObj,current_index}=this.data;
        console.log(goodsObj.skus)
        let prepay = await request({
            url: "my/order/wxpay",
            data: {
                description: "JSAPItest",
                //金额  待改
                total: 1,
                address: address['region'] + address['detailInfo'],
                phone: address['telNumber'],
                consignee: address['userName'],
                goodsId:goodsObj.goods_id,
                sku_Id:goodsObj.skus[current_index].SKU_Id
            },
            dataType: 'json',
            responseType: 'text',
            header: {
                'content-type': 'application/x-www-form-urlencoded',
                'Authorization': wx.getStorageSync('token')
            },
            method: 'POST',
        });
        console.log(prepay);
        prepay = JSON.parse(prepay);
        wx.requestPayment({
            nonceStr: prepay.nonceStr || "",
            package: prepay.package || "",
            paySign: prepay.paySign || "",
            timeStamp: prepay.timeStamp.toString() || "",
            signType: prepay.signType || "",
            "success": function(res) {
                wx.showToast({
                    title: '支付成功',
                }),
                wx.redirectTo({
                  url: '../order/order',
                })
            },
            "fail": function(err) {
                wx.showToast({
                    title: '支付失败',
                    icon: "error"
                })
            },
            "complete": function(res) {}
        })
    },

    // 获取当前地址
    getCurrentAddress() {
        const addressList = wx.getStorageSync('address_list') || [];
        const index = wx.getStorageSync('selected_index') || 0;
        return addressList[index];
    }
})